package crypto

import (
	"blueprint-crypto/internal/util"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"fmt"
	"os"
)

// RSA加密
func RSA_Encrypt(msgfilepath string, pempath string, outFile string) {

	//打开要加密文件
	plainText := util.Readfile(msgfilepath)
	//打开pem文件
	buf := util.Readfile(pempath)
	//pem解码
	block, _ := pem.Decode(buf)
	if block == nil {
		errors.New("publick key error")
	}
	//x509解码
	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic(err)
	}
	//类型断言
	publicKey := publicKeyInterface.(*rsa.PublicKey)
	//对明文进行加密
	cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
	if err != nil {
		panic(err)
	}
	//fmt.Println("加密后为byte：",cipherText)
	//fmt.Println("加密后为string：",string(cipherText))

	cipherfile, _ := os.Create(outFile)
	defer cipherfile.Close()
	cipherfile.Write(cipherText)
	fmt.Println(msgfilepath, "加密完成--", "加密后文件为：", outFile)
}
